<?php
/**
 * @author all@cosmos-framework.org
 * @copyright (c) 2013 cosmos-framework.org
 * @license http://www.opensource.org/licenses/mit-license.php
 * @link http://cosmos-framework.org/
 * @package cosmos.framework
 * @version 2.0
 */
namespace Cosmos\Http;

use \Cosmos\Invoker;

class Request extends Invoker {

    /**
     * @param string $methodName
     * @param mixed[] $methodArgs
     * @return mixed
     */
    public function __call($methodName, $methodArgs) {

        return parent::__call($methodName, $this->fillDefault($methodName, $methodArgs));
    }

    /**
     * @param string $methodName
     * @param mixed[] $methodArgs
     * @return mixed[]
     */
    protected function fillDefault($methodName, $methodArgs) {

        $fill = array();
        foreach ($this->methodParams($methodName) as $i => $param) {
            $p = &$fill[$i];
            if (array_key_exists($i, $methodArgs)) {
                $p = $methodArgs[$i];
            } elseif (isset($_REQUEST[$param->getName()])) {
                $p = $_REQUEST[$param->getName()];
            } elseif ($param->isDefaultValueAvailable()) {
                $p = $param->getDefaultValue();
            } else {
                $p = null;
            }
        }
        return $fill;
    }

    /**
     * @param string $methodName
     * @return ReflectionParameter[]
     */
    protected function methodParams($methodName) {

        return call_user_func($this->ref)->getMethod($methodName)->getParameters();
    }

}
